// 天天补贴
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:cbec_app/pages/goods/controller/daily_subsidy_ctr.dart';
import '../../../components/base/base_customize_segmented_control.dart';
import '../../../components/common/common_style.dart';
import '../../../components/common/count_down_timer.dart';
import '../../../components/common/not_found.dart';
import '../../../routes/routes.dart';
import '../binding/goods_detail_binding.dart';
import '../entity/activity_item_entity.dart';
import '../../../utils/Tools.dart';
import 'goods_detail_page.dart';

class DailySubsidyPage extends GetView<DailySubsidyCtr> {
  const DailySubsidyPage({super.key});

  List<Widget> _createItemWidgets() {
    final DailySubsidyCtr controller = Get.find<DailySubsidyCtr>();
    List<Widget> widgetArr = [];
    for (int i = 0; i < controller.itemList.length; i++) {
      ActivityItemEntity item = controller.itemList[i];
      int selectIndex = controller.selected;
      if (i == 0) {
        widgetArr.add(
          Container(
            padding: const EdgeInsets.only(left: 5, top: 5, bottom: 0, right: 5),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                CountDownTimer(
                  timeStamp: DateTime.parse(item.endtime ?? '').millisecondsSinceEpoch,
                  timeStyle: TimeStyle.hhmmss,
                  countDownStyle: CountDownStyle.box,
                  boxBackgroundColor: Tools.fromHex("#000000"),
                  colonColor: Tools.fromHex("#000000"),
                  style: setTextStyle(
                    12,
                    FontWeight.w400,
                    Tools.fromHex('#FFFFFF'),
                  ),
                  callback: () {},
                ),
                const SizedBox(
                  height: 5,
                ),
                Text(
                  '正在抢购',
                  style: TextStyle(
                    color: selectIndex == i ? Tools.fromHex('#F83F2D') : Tools.fromHex('#FFFFFF'),
                  ),
                ),
              ],
            ),
          ),
        );
      } else {
        widgetArr.add(
          Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                item.begintime ?? '',
                style: TextStyle(
                  color: selectIndex == i ? Tools.fromHex('#F83F2D') : Tools.fromHex('#FFFFFF'),
                ),
              ),
              const SizedBox(
                height: 3,
              ),
              Text(
                '即将开始',
                style: TextStyle(color: selectIndex == i ? Tools.fromHex('#F83F2D') : Tools.fromHex('#FFFFFF'), fontWeight: FontWeight.w500, fontSize: 12),
              ),
            ],
          ),
        );
      }
    }
    return widgetArr;
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<DailySubsidyCtr>(builder: (controller) {
      return Scaffold(
        //extendBodyBehindAppBar: true, // 允许 body 从 AppBar 顶部开始布局
        appBar: AppBar(
          backgroundColor: Colors.transparent, // 设置透明
          centerTitle: true,
          title: Text(
            '天天补贴',
            style: TextStyle(fontWeight: FontWeight.w500, fontSize: 17, color: Tools.fromHex('#333333')),
          ),
          leading: IconButton(
            icon: const Icon(
              Icons.arrow_back_ios,
              color: Colors.black,
            ),
            onPressed: () {
              Navigator.pop(context);
            },
          ),
        ),
        body: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            //自适应高度的图片
            Stack(
              children: [
                SizedBox(
                  width: double.infinity,
                  child: Image.asset("assets/images/daily_subsidy_bg.png", fit: BoxFit.fitWidth),
                ),
                //const topRightBox(),
              ],
            ),

            // 分段控件
            SizedBox(
              height: 60,
              child: BaseCustomizeSegmentedControl(
                items: _createItemWidgets(),
                selectedIndex: controller.selected,
                onChanged: (index) {
                  controller.change(index);
                },
              ),
            ),

            // 列表
            Expanded(
              child: controller.goodsList.isNotEmpty
                  ? Tools.getPullRefresh(
                      enablePullDown: true,
                      enablePullUp: true,
                      refreshController: controller.baseRefreshCtr,
                      onRefresh: controller.onPageRefresh,
                      onLoading: controller.onPageLoading,
                      child: ListView.builder(
                          controller: controller.scrollController,
                          padding: EdgeInsets.zero, // 移除默认的内边距
                          itemCount: controller.goodsList.length,
                          itemBuilder: (context, index) {
                            final Map item = controller.goodsList[index];
                            return _createItem(item);
                          }))
                  : const NotFound(),
            ),
          ],
        ),
      );
    });
  }

  Widget _createItem(Map item) {
    return GestureDetector(
      onTap: () {
        final id = item['goodsId'];
        Get.to(
          () => GoodsDetailPage(flag: id), // 使用函数懒加载页面实例
          routeName: '${Routes.goodsDetail}?unique=${DateTime.now().millisecondsSinceEpoch}',
          arguments: {"id": id}, // 传递其它参数
          binding: GoodsDetailBinding(flag: id), // 将 tag 参数传递给绑定类
        );
      },
      child: Container(
        color: Tools.fromHex('#F4F4F4'),
        child: Container(
          margin: const EdgeInsets.only(left: 10, right: 10, top: 10), // 添加外边距
          child: ClipRRect(
            borderRadius: BorderRadius.circular(8), // 设置圆角裁剪
            child: Container(
              decoration: const BoxDecoration(
                color: Colors.white, // 白色背景
              ),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start, // 使列顶部对齐
                children: [
                  Padding(
                    padding: const EdgeInsets.symmetric(vertical: 8),
                    child: Image.network(item['mainImage'], width: 120, height: 120),
                  ),
                  Expanded(
                    // 确保文本可以占据剩余空间
                    child: Container(
                      height: 130,
                      padding: const EdgeInsets.only(left: 10, right: 10, top: 5, bottom: 5), // 添加外边距
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        crossAxisAlignment: CrossAxisAlignment.start, // 左对齐文本
                        children: [
                          RichText(
                            text: TextSpan(
                              children: [
                                WidgetSpan(
                                  child: goodsTypeTag(
                                    getGoodsTypeName(item['commodityType']),
                                    margin: const EdgeInsets.only(right: 5), // 设置右边距
                                  ),
                                ),
                                TextSpan(
                                  text: item['commodityName'],
                                  style: TextStyle(
                                    fontSize: 14,
                                    fontWeight: FontWeight.normal,
                                    color: Tools.fromHex('#3D3D3D'),
                                  ),
                                ),
                              ],
                            ),
                            maxLines: 2, // 设置最大行数为 2
                            overflow: TextOverflow.ellipsis, // 超过部分显示省略号
                          ),

                          // 标签
                          Wrap(
                            runSpacing: 8.w,
                            children: [
                              for (var text in item['discountLabel'])
                                BorderedText(
                                  text: text,
                                  padding: const EdgeInsets.only(left: 2, right: 2, top: 2, bottom: 2),
                                  borderColor: Tools.fromHex('#E6C197'),
                                  textStyle: TextStyle(
                                    fontSize: 12,
                                    color: Tools.fromHex('#E6C197'),
                                    fontWeight: FontWeight.w300,
                                  ),
                                ),
                            ],
                          ),
                          Stack(
                            children: [
                              Image.asset('assets/images/daily_subsidy_item.png'),
                              Positioned.fill(
                                  child: Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: [
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.start,
                                    children: [
                                      Padding(
                                        padding: const EdgeInsets.only(left: 8),
                                        child: Column(
                                          mainAxisAlignment: MainAxisAlignment.spaceAround,
                                          crossAxisAlignment: CrossAxisAlignment.start, // 左对齐文本
                                          children: [
                                            Text(
                                              '日常价格 ¥${item['price'].toString()}',
                                              style: TextStyle(
                                                color: Tools.fromHex('#EE855D'),
                                                fontWeight: FontWeight.w500,
                                                fontSize: 12,
                                                decoration: TextDecoration.lineThrough, // 添加删除线
                                                decorationColor: Tools.fromHex('#EE855D'), // 设置删除线的颜色
                                                decorationThickness: 1.5, // 设置删除线的粗细（可选）
                                              ),
                                            ),
                                            Text.rich(
                                              TextSpan(
                                                children: [
                                                  TextSpan(
                                                    text: '补贴到手价 ¥', // 前面的文字
                                                    style: TextStyle(
                                                      color: Tools.fromHex('#E6452F'),
                                                      fontWeight: FontWeight.w500,
                                                      fontSize: 12, // 正常字体大小
                                                    ),
                                                  ),
                                                  TextSpan(
                                                    text: '${item['specialPrice']}', // 需要变大字体的部分
                                                    style: TextStyle(
                                                      color: Tools.fromHex('#E6452F'),
                                                      fontWeight: FontWeight.w700,
                                                      fontSize: 15, // 设置更大的字体大小
                                                    ),
                                                  ),
                                                ],
                                              ),
                                            ),
                                          ],
                                        ),
                                      ),
                                    ],
                                  ),
                                  Padding(
                                    padding: const EdgeInsets.only(right: 16),
                                    child: Column(
                                      children: [
                                        const Text(
                                          '已补贴',
                                          style: TextStyle(color: Colors.white, fontSize: 12, fontWeight: FontWeight.w500),
                                        ),
                                        Text(
                                          '${item['discount']}元',
                                          style: const TextStyle(color: Colors.white, fontSize: 12, fontWeight: FontWeight.w500),
                                        ),
                                      ],
                                    ),
                                  )
                                ],
                              ))
                            ],
                          )
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}
